'use strict';

module.exports = app => {
  class TemController extends app.Controller {    
    * create(){
      const ctx = this.ctx;    
      const data = ctx.request.body;
      console.log(ctx.request.query);
      console.log(ctx.request.params);
      ctx.logger.info(data);  
      const rule = {
        data: {
          type: "json",
          required: true
        }
      };
      ctx.validate(rule, { data });   
      try{
        const rs = yield ctx.service.job.add(data);      
        this.success({ rs });
      }catch(err){ 
        ctx.logger.error(new Error(err));         
        this.error({error:err.errno,msg:err.sqlMessage});      
      }
    }  

    * show(){
      const ctx = this.ctx;
      const params = ctx.params; 
      ctx.logger.info(params);
      try {
        const record = yield ctx.service.job.getOneByOption({ id: params.id });
        this.success({ record });
      } catch (err) {
        ctx.logger.error(new Error(err));
        this.error({ error: err.errno, msg: err.sqlMessage });
      }
    }

    * update(){
      const ctx = this.ctx;
      const body = ctx.request.body;  
      const rule = {      
          body:{
            type: "json",
            required: true 
          }      
      };
      ctx.validate(rule, { body });   
      const params = ctx.params;      
      const option = {};
      Object.assign(option, { _id: params.id },body);        
      ctx.logger.info(option);
      try {
        const records = yield ctx.service.job.update(params.id, body);
        this.success({ records});
      } catch (err) {
        ctx.logger.error(new Error(err));
        this.error({ error: err.errno });
      }
    }

    * index(){
      const ctx = this.ctx;
      const query = ctx.request.query;
      
      ctx.logger.info(query);
      try {
        const records = yield ctx.service.job.getList(query);
        this.success(records);
      } catch (err) {
        ctx.logger.error(new Error(err));
        this.error({ error: err.errno, msg: err.sqlMessage });
      }
    }
    * destroy(){
      const ctx = this.ctx;
     // const body = ctx.request.body;
      const params = ctx.params;
      ctx.logger.info(params);    
      
      try {
        const result = yield ctx.service.job.delete({ id : params.id });
        this.success({ result  });
      } catch (err) {
        ctx.logger.error(new Error(err));
        this.error({ error: err.errno, msg: err.sqlMessage });
      }
    }
  }
  return TemController;
};

